< previous page page_175 next page >

Page 175
The method, testMethod, still executes but displays the wrong data (in this case, it displays the error number of the Type Mismatch error). You need to build in the ability to prevent further execution of the method when such an error occurs. Thus, you would need to modify testMethod as follows:
Public Sub testMethod(ByVal argVariant As Variant)
    Dim iInteger As Integer
    If VarType(argVariant) = vbInteger Then
        iInteger = argVariant
        MsgBox iInteger
    End If
End Sub
Note that this method assumes that you want the flexibility of having an argument of any Visual Basic data type. The variable iInteger is set to the value of argument argVariant if argVariant is internally stored as an Integer. In addition, if argVariant is internally an Integer, the value of iInteger is displayed in a message box. It's good practice to use a local variable instead of the actual argument for internal method implementation code. In any case, if you try to pass in any value that is not an Integer, the testMethod method will ignore the request. If the value is an Integer, this method will be able to process the request.
This pattern of type checking does not apply only to intrinsic data types such as Integer and String. You can use the pattern for Object data types, whether Visual Basic or your own. In the preceding example, you'd simply replace Integer with some interface or implementation object of your choosing, such as the following:
Public Sub testMethod(ByVal argObject As Object)
    Dim theBasicPersonalChecking As BasicPersonalChecking
    If TypeName(argObject) = BasicPersonalChecking Then
        Set theBasicPersonalChecking = argObject
        MsgBox theBasicPersonalChecking.AccountNumber
    End If
End Sub
You could allow Visual Basic to enforce the argument object type by replacing the generic type Object with theBasicPersonalChecking; however, if you need the flexibility of accepting any type of object (for processing by more than one internal private method), you need to do the type checking yourself.
Using Return Data Type Checking
Related to type checking for method arguments is type checking for returned values and objects. The idea here is to make sure that the type of the variable or object returned is of the expected type. Listing 8.1 shows an example of return type testing using the previous example code as the basis.

 
< previous page page_175 next page >

If you like this book, buy it!